package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
	"time"
)

type CommonController struct {
	beego.Controller
}

type PackageModel struct {
	Libname string
	LibIndex int
	LibExists bool
}

func (this *CommonController) RetData(resp map[string]interface{}) {
	resp["version"] = 1.01
	this.Data["json"] = resp
	this.ServeJSON()
}

func ExcuteGoGet(githubAddress string)bool{
	go goGet(githubAddress)
	var watiTimes uint32 = 10*15*1000
	beginTime := time.Now()
	if len(strings.TrimSpace(githubAddress))<=0{
		return  false
	}
	for {
		path := GO_PATH+"\\src\\"+githubAddress
		path = strings.ReplaceAll(path,"\\","/")
		exists := IsExist(path)
		if !exists  {
			continue
		}
		m,s := ioutil.ReadDir(path)
		if s!=nil{
			return false
		}
		if len(m) >2 {
			//fmt.Println("000000000000000000000000002")
			return true
		}
		endTimes := time.Now()
		timeDif := uint32(endTimes.Sub(beginTime).Seconds()*1000)
		//fmt.Println(timeDif)
		//fmt.Println(watiTimes)
		if timeDif > watiTimes{
			//fmt.Println("000000000000000000000000006")
			return false
		}
	}
	//fmt.Println("000000000000000000000000001")
	return false
}

func goGet(githubAddress string){
	c := exec.Command("cmd", "/C", "go get ", githubAddress)
	if err := c.Run(); err != nil {
		fmt.Println("Error: ", err)
	}
}

func IsExist(f string) bool {
	_, err := os.Stat(f)
	return err == nil || os.IsExist(err)
}